package com.sino.tb.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Title:
 *
 * Copyright
 *
 * @author Tony Zeng(zeng_shengb0@163.com)
 * @version
 *
 * created on 2005-7-15 15:47:12
 *
 * modify on :
 *
 * note:
 **/

public class MD5 implements Verify{

    public final static char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                                             'a', 'b', 'c', 'd', 'e', 'f' };
    private MessageDigest mDigest = null;

    public MD5(){
        try{
        this.mDigest=MessageDigest.getInstance("MD5");
        }catch(NoSuchAlgorithmException naex){
            naex.printStackTrace();
        }
    }

    public String getCode(String s) {
        try {
            mDigest.update(s.getBytes());
            byte[] md = mDigest.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = MD5.hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = MD5.hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String getCode(byte[] ba){
        String s=null;
        if(ba!=null){
            return null;
        }else{
            return this.getCode(new String(ba));
        }
    }

    public static void main(String argc[]) {
        MD5 md=new MD5();
        System.out.println(md.getCode("200511170120205020201").substring(0,8));
    }

}
